package com.dylan.历史.多线程.并发编程的艺术.锁;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Created by Dylan on 2018/9/19.
 *
 * 多次同时获取锁
 */
public class MultiLock implements Lock {

    private class Sync extends AbstractQueuedSynchronizer {

        /**
         * 在此定义同时获取锁的数量
         */
        Sync(int count) {
            if (count <= 0) {
                throw new IllegalArgumentException("count must > 0");
            }
            setState(count);
        }

        @Override
        protected int tryAcquireShared(int reduceCount) {
            int current = getState();
            int newCount = current - reduceCount;
            if (newCount < 0 || compareAndSetState(current, newCount)) {
                return newCount;
            }
            return -1;
        }

        /**
         * 该方法是有问题的，无法确保在释放锁之前是获取到了锁
         */
        @Override
        protected boolean tryReleaseShared(int returnCount) {
            for (;;) {
                int current = getState();
                int newCount = current + returnCount;
                if (compareAndSetState(current, newCount)) {
                    return true;
                }
            }
        }
    }

    private Sync sync;

    MultiLock(int count) {
        sync = new Sync(count);
    }


    @Override
    public void lock() {
        sync.acquireShared(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquireShared(1) >= 0;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sync.releaseShared(1);
    }

    @Override
    public Condition newCondition() {
        throw new UnsupportedOperationException();
    }
}
